package com.mypackage.diary.service.user;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mypackage.diary.dao.security.UserDao;
import com.mypackage.diary.model.Authority;
import com.mypackage.diary.model.Userprofile;
import com.mypackage.diary.mymodel.User;

@Service
@Transactional
public class UserService implements UserDetailsService{

	@Autowired
	private UserDao userDao;
	
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}


	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		Userprofile userProfile = userDao.loadUserByEmail(username);
		
		if(userProfile == null){
			return null;
		}
		
		User user = new User();
		
		user.setUserId(userProfile.getId());
		user.setUsername(userProfile.getUsername());
		user.setEmail(userProfile.getEmail());
		user.setPassword(userProfile.getPassword());
		user.setEnabled(userProfile.getEnabled());
		
		user.setAuthorities(getAuthorities(userProfile.getAuthority().getRole()));
		
		return user;
	}
	

	// set RoLE for user
    public Set<GrantedAuthority> getAuthorities(String role) {
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority(role));
        return authorities;
    }

}
